package cn.school.web.controller.client;

import cn.school.common.core.controller.BaseController;
import cn.school.system.config.FriendsConfig;
import cn.school.system.domain.BiShop;
import cn.school.system.domain.BiWxUser;
import cn.school.system.model.req.WxAuthorizeDTO;
import cn.school.system.model.resp.WxAccessTokenRespDTO;
import cn.school.system.service.IBiShopService;
import cn.school.system.service.IBiWxUserService;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author zsj
 * @version 1.0
 * @date 2023/12/5 13:29
 * @desc
 **/
@Slf4j
@Controller
@RequestMapping(value = "/h5/wxauth")
public class H5WxAuthController extends BaseController {
    @Autowired
    private FriendsConfig friendsConfig;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IBiShopService shopService;
    @Autowired
    private IBiWxUserService wxUserService;

    @GetMapping("/authorize")
    public String authorize(WxAuthorizeDTO dto){
        //需要编码
        String redirectUri = friendsConfig.getDomain() + "/prod-api/h5/wxauth/index";
        try {
            redirectUri = URLEncoder.encode(redirectUri, "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }

        StringBuilder url = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
        url.append("appid=").append(friendsConfig.getWxAppid());
        url.append("&redirect_uri=").append(redirectUri);
        url.append("&response_type=code&scope=snsapi_base&state=");
        if(StringUtil.isNotEmpty(dto.getWxstate())){
            url.append(dto.getWxstate());
        }
        url.append("#wechat_redirect");

        log.info("跳转微信：{}", url.toString());

        return "redirect:"+url.toString();
    }

    @GetMapping("/index")
    public String index(@RequestParam Map<String,String> para) throws Exception{
        log.info("收到微信回调，参数：{}", JSON.toJSONString(para));
        String state = para.get("state");
        if(StringUtil.isEmpty(state)){
            state = "";
        }
        String code = para.get("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ friendsConfig.getWxAppid()+"&secret="+friendsConfig.getWxSecret()+"&code="+code+"&grant_type=authorization_code";
        ResponseEntity<WxAccessTokenRespDTO> response = restTemplate.getForEntity(url, WxAccessTokenRespDTO.class);
        String indexUrl = "";
        if(response.getStatusCode()== HttpStatus.OK) {
            WxAccessTokenRespDTO respDTO = response.getBody();
            log.info("获取token接口，返回参数：{}", JSON.toJSONString(para));
            if (StringUtils.hasText(respDTO.getOpenid())) {
                indexUrl = friendsConfig.getDomain() + "/phone?sid="+state+"&oid="+ respDTO.getOpenid();
                //保存用户
                saveWxUser(state,respDTO.getOpenid());
            } else {
                throw new Exception("未获取到微信id");
            }
        }else{
            throw new Exception("请求微信错误");
        }

        log.info("收到微信回调后，再次转发");
        return "redirect:"+indexUrl;
    }

    //保存微信用户
    private void saveWxUser(String shopId,String openid){
        //通过openid查询用户
        BiWxUser queryTemp=new BiWxUser();
        queryTemp.setOpenid(openid);
        List<BiWxUser> wxUserList = wxUserService.selectBiWxUserList(queryTemp);
        if(wxUserList==null || wxUserList.size()<=0){
            BiWxUser wxUser = new BiWxUser();

            if(StringUtil.isNotEmpty(shopId)) {
                BiShop shop = shopService.selectBiShopById(Long.parseLong(shopId));
                if (shop!=null){
                    wxUser.setParentShopId(shop.getId());
                    wxUser.setParentShopName(shop.getShopName());
                    wxUser.setParentShopPhone(shop.getPhone());
                }
            }

            wxUser.setOpenid(openid);

            wxUserService.insertBiWxUser(wxUser);
        }
    }
}
